package common

import (
	"github.com/dgrijalva/jwt-go"
	"time"
	"errors"
)

type TokenUserInfo struct {
	UserId string
	Username string
}

func CreateToken(user *TokenUserInfo)(tokenss string,err error){
	//自定义claim
	claim := jwt.MapClaims{
		"id":       user.UserId,
		"username": user.Username,
		"nbf":      time.Now().Unix(),
		"iat":      time.Now().Unix(),
		"exp":		time.Now().Unix() + 24*60*60, // 1 天后过期
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256,claim)
	tokenss,err  = token.SignedString([]byte(AuthConf.JwtSecret))
	return
}


func secret()jwt.Keyfunc{
	return func(token *jwt.Token) (interface{}, error) {
		return []byte(AuthConf.JwtSecret),nil
	}
}


func ParseToken(tokenss string)(user *TokenUserInfo ,newToken string, err error){
	user = &TokenUserInfo{}
	token,err := jwt.Parse(tokenss,secret())
	if err != nil{
		return
	}
	claim,ok := token.Claims.(jwt.MapClaims)
	if !ok{
		err = errors.New("cannot convert claim to mapclaim")
		return
	}
	//验证token，如果token被修改过则为false
	if  !token.Valid{
		err = errors.New("token is invalid")
		return
	}

	user.UserId =  claim["id"].(string)
	user.Username = claim["username"].(string)

	timeExp , ok := claim["exp"].(int64)
	if !ok {
		err = errors.New("exp time invalid ")
	}
	if time.Now().Unix() > timeExp &&  timeExp <  time.Now().Unix()+60*60*48 {
		newToken,err = CreateToken(user)
	}else{
		err = errors.New("token is invalid ,time out")
	}

	return
}